package com.wu.strtoint;

/**
 * 把字符串转成整数
 *
 * @author lynn
 * @date 2020/8/17 - 9:55
 */
public class Solution {
    public int StrToInt(String str) {
        if (str == null || "".equals(str) || str.equals("0")) {
            return 0;

        }
        boolean flag = true;
        int index = 0;

        if (str.charAt(0) == '-') {
            flag = false;
            index = 1;
        } else if (str.charAt(0) == '+') {
            flag = true;
            index = 1;
        }
        long result = 0;
        for (int i = index; i < str.length(); i++) {
            char c = str.charAt(i);
            if ('0' <= c && c <= '9') {
                result = result * 10 + (c - '0');
                if (flag == true && result > Integer.MAX_VALUE) {
                    throw new RuntimeException("上溢出");
                }
                if (flag == false && result < Integer.MIN_VALUE) {
                    throw new RuntimeException("下溢出");
                }
            } else {
                return 0;
            }
        }

        if (flag == false) {
            return (int) (-1 * result);
        } else {
            return (int) result;
        }
    }
}
